package main

import (
	"flag"
	"fmt"
	"io"
	"net"
	"os"
)

type Client struct {
	ServerIp string
	ServerPort int
	Conn net.Conn
	Name string
	No int
}

func NewClient(serverIp string, serverPort int) *Client {

	client := &Client{
		ServerIp: serverIp,
		ServerPort: serverPort,
		No: 999,
	}
	conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", serverIp, serverPort))
	if err != nil {
		fmt.Println("net.dial err :", err)
		return nil
	}

	client.Conn = conn

	return client
}

var serverIp string
var serverPort int

func init() {
	flag.StringVar(&serverIp, "ip", "127.0.0.1", "默认ip地址127.0.0.1")
	flag.IntVar(&serverPort, "port", 8888,"默认端口8888")
}

func (c *Client) Menu() bool {

	var flag int
	fmt.Println("1.公聊模式")
	fmt.Println("2.私聊模式")
	fmt.Println("3.更新用户名")
	fmt.Println("0.退出")

	fmt.Scanln(&flag)
	if flag >= 0 && flag <= 3 {
		c.No = flag
		return true
	} else {
		fmt.Println("请选择正确的选项")
		return false
	}
}

func (c *Client) UpdateName() bool {

	fmt.Println("请输入新的用户名:")
	fmt.Scanln(&c.Name)
	sendMsg := "rename|" + c.Name + "\n"
	_, err := c.Conn.Write([]byte(sendMsg))
	if err != nil {
		fmt.Println("发送失败: ", err)
		return false
	}
	return true
}

func (c *Client) PublicChat() {

	fmt.Println("请输入聊天内容,退出请输入exit")
	var publicMsg string
	fmt.Scanln(&publicMsg)
	for publicMsg != "exit" {
		if len(publicMsg) != 0 {
			_, err := c.Conn.Write([]byte(publicMsg))
			if err != nil {
				fmt.Println("conn write err : ", err)
			}
		}
		publicMsg = ""
		fmt.Println("请输入聊天内容,退出请输入exit")
		fmt.Scanln(&publicMsg)
	}
}

func (c *Client) selectUser() {
	sendMsg := "who\n"
	_, err := c.Conn.Write([]byte(sendMsg))
	if err != nil {
		fmt.Println("con writer err ：", err)
		return
	}
}
func (c *Client) PrivateChat() {

	c.selectUser()
	var toUserName string
	var msg string
	fmt.Println("请输入聊天对象【用户名】，exit退出")
	fmt.Scanln(&toUserName)
	fmt.Println("请输入聊天内容，exit退出")
	fmt.Scanln(&msg)

	for toUserName != "exit" && msg != "exit" {
		if len(msg) != 0 {
			sendMsg := "to|" + toUserName + "|" + msg
			_, err := c.Conn.Write([]byte(sendMsg))
			if err != nil{
				fmt.Println("conn Write err:", err)
				break
			}
			msg = ""
			fmt.Println("请输入聊天内容，exit退出")
			fmt.Scanln(&msg)
		}
		fmt.Println("请输入聊天对象【用户名】，exit退出")
		fmt.Scanln(&toUserName)
	}
}

func (c *Client) Run() {

	for c.No != 0 {
		if c.Menu() == true {
			switch c.No {
			case 1:
				c.PublicChat()
				break
			case 2:
				c.PrivateChat()
				break
			case 3:
				c.UpdateName()
				break
			}
		}
	}
}

func (c *Client) readResponse() {

	io.Copy(os.Stdout, c.Conn)
}

func main() {

	flag.Parse()
	client := NewClient(serverIp, serverPort)
	if client == nil {
		fmt.Println("服务器链接失败")
		return
	}

	fmt.Println("链接成功")

	go client.readResponse()

	client.Run()

}

